<?php
class Configuration{
  private $configFile = 'config.ini';
  private $items = array();

  function __construct() { 
    $this->parse(); 
  }

  function __get($id) {
    return $this->items[$id]; 
  }

  function __set($id, $v) { 
    $this->items[$id] = $v; 
  }

  function parse() {
    $fh = fopen($this->configFile, 'r');

    while ($l = fgets($fh)) {
      $l = str_replace("\r", "", $l);
      if (preg_match('/^#/', $l) == false) {
        preg_match('/^(.*?)=(.*?)$/', $l, $found);
        $this->items[$found[1]] = $found[2];
      }
    }

    fclose ($fh);
  }

  function save() {
    $nf = '';
    $fh = fopen($this->configFile, 'r');

    while ($l = fgets($fh)) {
      if (preg_match('/^#/', $l) == false) {
        preg_match('/^(.*?)=(.*?)$/', $l, $found);
        $nf .= $found[1] . "=" . $this->items[$found[1]].PHP_EOL;
      } else { 
        $nf .= $l; 
      }
    }

    fclose ($fh);
    //uncomment next line to create a backup copy before save
    //copy($this->configFile, $this->configFile . '.bak');
    $fh = fopen($this->configFile, 'w');
    fwrite($fh, $nf);
    fclose ($fh);
  }
}
?>